package com.zl.tby.screen.service.impl;

import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.model.TbyAnimalPlant;
import com.zl.tby.screen.service.ITbyAnimalPlantScreenService;
import com.zl.tby.screen.vo.animalPlant.TbyAnimalPlantScreenBean;
import com.zl.tby.screen.vo.animalPlant.TbyAnimalPlantScreenQuery;
import com.zl.tby.vo.bean.SpeciesLegendBean;
import org.noear.solon.annotation.Component;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static java.math.BigDecimal.ROUND_HALF_UP;

/**
 * 动植物-大屏
 * @author sunjiaxing
 * @version 1.0
 * @since 2024/8/16 23:12
 */
@Component
public class TbyAnimalPlantScreenServiceImpl  implements ITbyAnimalPlantScreenService {

    @Db
    private DbContext db;

    @Override
    public List<TbyAnimalPlantScreenBean> getSpecies(Long typeLevel) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereTrue()
                .andIf(true,"(c.id = ?", typeLevel).or("c.parent_id = ? )", typeLevel);
                //.andIf(true,"c.parent_id <> ?", 0L);
        try {
            return dbTableQuery.andIf(true,"is_species = ?", "0").selectList("a.id as id, a.files files, a.ch_name ch_name,a.flagship_species_seq flagship_species_seq", TbyAnimalPlantScreenBean.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getTypeLevel(Long typeLevel,String protectionLevel) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .leftJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereTrue()
                .andIf(true,"(c.id = ?", typeLevel).or("c.parent_id = ? )", typeLevel)
                .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level = ?", protectionLevel)
                //扣除无的
                .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level != ?","level_7");
        try {
            long total = dbTableQuery.selectCount();
            dbTableQuery.groupBy("a.type_level").orderByAsc("c.id");
            List<TbyAnimalPlantScreenBean> list = dbTableQuery.selectList("a.id as id, a.type_level as type_level, c.category_name as category_name, count(a.id) as num,sum(a.wz_boundary) as wz_boundary,sum(a.wz_phylum) as wz_phylum,sum(a.wz_correct) as wz_correct,sum(a.wz_catalogue) as wz_catalogue,sum(a.wz_section) as wz_section,sum(a.wz_genus) as wz_genus,sum(a.wz_species) as wz_species", TbyAnimalPlantScreenBean.class);
            list.forEach(item -> {
                item.setTotal(total);
                String name =  item.getWzCatalogue()+"目"+item.getWzSection()+"科"+item.getWzGenus()+"属";
                item.setName(name);
                BigDecimal percent = BigDecimal.valueOf(item.getNum()).divide(BigDecimal.valueOf(total),4,ROUND_HALF_UP);
                item.setPercent(percent.multiply(new BigDecimal("100")));
            });
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getAnimalTypeLevel(Long typeLevel,String protectionLevel) {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        try {
            DbTableQuery dbTableCategory = db.table("tby_species_category a").whereTrue().and("a.parent_id = ? ", typeLevel).orderByAsc("a.sort");
            List<TbyAnimalPlantScreenBean> listCategory = dbTableCategory.selectList("a.id type_level,a.category_name as category_name", TbyAnimalPlantScreenBean.class);
            if (listCategory != null && listCategory.size() > 0) {
                for(TbyAnimalPlantScreenBean itemC: listCategory){
                    DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                            .whereTrue()
                            .andIf(true,"a.type_level = ?", itemC.getTypeLevel())//只统计顶级分类以下的
                            .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level = ?", protectionLevel)
                            //扣除无的
                            .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level != ?","level_7");
                    dbTableQuery.groupBy("a.type_level");
                    List<TbyAnimalPlantScreenBean> listA = dbTableQuery.selectList("a.id as id, a.type_level as type_level, count(a.id) as num,sum(a.wz_boundary) as wz_boundary,sum(a.wz_phylum) as wz_phylum,sum(a.wz_correct) as wz_correct,sum(a.wz_catalogue) as wz_catalogue,sum(a.wz_section) as wz_section,sum(a.wz_genus) as wz_genus,sum(a.wz_species) as wz_species", TbyAnimalPlantScreenBean.class);
                    TbyAnimalPlantScreenBean dto  = new TbyAnimalPlantScreenBean();
                    dto.setCategoryName(itemC.getCategoryName());
                    dto.setTypeLevel(itemC.getTypeLevel());
                    if (listA != null && listA.size() > 0) {
                        String name =  listA.get(0).getWzCatalogue()+"目"+listA.get(0).getWzSection()+"科"+listA.get(0).getWzGenus()+"属";
                        dto.setName(name);
                        dto.setNum(listA.get(0).getNum());
                    } else {
                        String name =  "0目"+"0科"+"0属";
                        dto.setName(name);
                        dto.setNum(0L);
                    }
                    list.add(dto);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getPlantTypeLevel(Long typeLevel,String protectionLevel) {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        List<TbyAnimalPlantScreenBean> listCategory = new ArrayList<>();
        try {
            DbTableQuery dbTableCategory = db.table("tby_species_category a")
                .whereTrue()
                .and("a.parent_id = ? ", typeLevel).orderByAsc("a.sort");
            listCategory = dbTableCategory.selectList("a.id type_level,a.category_name as category_name",TbyAnimalPlantScreenBean.class);
            if(listCategory!=null&&listCategory.size()>0) {
                for (TbyAnimalPlantScreenBean itemC : listCategory) {
                    DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                            .whereTrue()
                            .andIf(true,"a.type_level = ?", itemC.getTypeLevel())//只统计顶级分类以下的
                            .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level = ?", protectionLevel)
                            .andIf(StringUtils.isNotEmpty(protectionLevel),"a.protection_level != ?","level_7"); //扣除无的
                    dbTableQuery.groupBy("a.type_level");
                    List<TbyAnimalPlantScreenBean> listA = dbTableQuery.selectList("a.id as id, a.type_level as type_level,count(a.id) as num,sum(a.wz_boundary) as wz_boundary,sum(a.wz_phylum) as wz_phylum,sum(a.wz_correct) as wz_correct,sum(a.wz_catalogue) as wz_catalogue,sum(a.wz_section) as wz_section,sum(a.wz_genus) as wz_genus,sum(a.wz_species) as wz_species", TbyAnimalPlantScreenBean.class);
                    TbyAnimalPlantScreenBean dto  = new TbyAnimalPlantScreenBean();
                    dto.setTypeLevel(itemC.getTypeLevel());
                    dto.setCategoryName(itemC.getCategoryName());
                    if(listA!=null&&listA.size()>0){
                        String name =  listA.get(0).getWzCatalogue()+"目"+listA.get(0).getWzSection()+"科"+listA.get(0).getWzGenus()+"属";
                        dto.setName(name);
                        dto.setNum(listA.get(0).getNum());
                    }else{
                        String name =  "0目"+"0科"+"0属";
                        dto.setName(name);
                        dto.setNum(0L);
                    }
                    list.add(dto);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public Long searchTotalCountByProtectionLevel(String protectionLevel, Long topId) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereTrue()
                .andIf(true,"(c.id = ?", topId).or("c.parent_id = ?)", topId)
                //.andNeq("c.parent_id", 0L)
                .andEq("a.protection_level", protectionLevel)
                .andNeq("a.protection_level", "level_7");
        try {
            return dbTableQuery.selectCount();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Long searchTotalCountByProp(String prop, Long topId) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereTrue()
                .andIf(true,"(c.id = ?", topId).or("c.parent_id = ?)", topId)
                //.andIf(true,"c.parent_id <> ?", 0L)
                .and("a." + prop + " <> ?", "0");
        try {
            return dbTableQuery.selectCount();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Long searchTotalCountByEcology(String ecology) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereEq("a.ecology", ecology);
        try {
            return dbTableQuery.selectCount();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0L;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getProtection(String[] array, String[] levelArray, String[] otherArray, Long topId) {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            TbyAnimalPlantScreenBean dto = new TbyAnimalPlantScreenBean();
            String val = levelArray[i];
            dto.setValue(searchTotalCountByProtectionLevel(val, topId));
            dto.setName(array[i]);
            dto.setProtectionLevel(val);
            list.add(dto);
        }
        for (int i = 0; i < otherArray.length; i++) {
            TbyAnimalPlantScreenBean dto = new TbyAnimalPlantScreenBean();
            String val = otherArray[i];
            dto.setValue(searchTotalCountByProp(val, topId));
            dto.setName(otherArray[i]);
            dto.setProtectionLevel(val);
            list.add(dto);
        }
        return list;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getProtectionByPlant() {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        String[] array = {"一级保护植物", "二级保护植物", "省重点保护植物"};
        String[] levelArray = {"level_1", "level_2", "level_6"};
        for (int i = 0; i < array.length; i++) {
            TbyAnimalPlantScreenBean dto = new TbyAnimalPlantScreenBean();
            String val = levelArray[i];
            dto.setValue(searchTotalCountByProtectionLevel(val, 2L));
            dto.setName(array[i]);
            dto.setProtectionLevel(val);
            list.add(dto);
        }
        String[] otherArray = {"iucn", "cites"};
        for (int i = 0; i < otherArray.length; i++) {
            TbyAnimalPlantScreenBean dto = new TbyAnimalPlantScreenBean();
            String val = otherArray[i];
            dto.setValue(searchTotalCountByProp(val, 2L));
            dto.setName(otherArray[i]);
            dto.setProtectionLevel(val);
            list.add(dto);
        }
        return list;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getTSWZ(TbyAnimalPlantScreenQuery dto) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
            .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
            .whereTrue()
            .and().begin("c.id = ?", dto.getType()).or("c.parent_id = ?", dto.getType()).end()
            //.andIf(true,"c.parent_id <> ?", 0L)
            .andIf(dto.getTypeLevel() != null && dto.getTypeLevel() != 0L,"a.type_level = ?", dto.getTypeLevel())
            .andIf(StringUtils.isNotEmpty(dto.getEcology()), "a.ecology = ?", dto.getEcology());
        //}
        try {
            dbTableQuery.andIf(StringUtils.isNotEmpty(dto.getChName()), "a.ch_name like ?", "%" + dto.getChName() + "%");
            if (StringUtils.isNotEmpty(dto.getProtectionLevel())) {
                String type = ",cites,iucn,";
                if (type.indexOf("," + dto.getProtectionLevel() + ",") > -1) {
                    // 特殊的两项
                    dbTableQuery.and("a." + dto.getProtectionLevel() + " <> ?", "0");
                } else if (dto.getProtectionLevel().equals("cherish")) {
                    // 中国珍惜濒危真菌物种
                    dbTableQuery.andEq("a.is_cherish", 1);
                } else {
                    dbTableQuery.andIf(StringUtils.isNotEmpty(dto.getProtectionLevel()),"a.protection_level = ?", dto.getProtectionLevel())
                            .andIf(StringUtils.isNotEmpty(dto.getProtectionLevel()),"a.protection_level != ?","level_7");
                }
            }
            dbTableQuery.orderByAsc("c.sort");
            List<TbyAnimalPlantScreenBean> list = dbTableQuery.selectList("a.id id, a.files files, a.ch_name ch_name,a.latitude_longitude latitude_longitude,a.layer_name layer_name, a.thumbnail thumbnail_url, a.thumbnail_icon", TbyAnimalPlantScreenBean.class);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getChangeTrend(TbyAnimalPlantScreenQuery dto) throws ParseException {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        String startYear = ToolsUtil.splitStr(dto.getStartTime(), '-')[0];
        String endYear = ToolsUtil.splitStr(dto.getEndTime(), '-')[0];
        // 开始结束时间是同一年的情况下，只显示月份，开始和结束时间不是同一年的情况下，显示yyyy-MM
        boolean sameYear = startYear.equals(endYear);
        ArrayList<String> arr = getMiddleMonth(dto.getStartTime(),dto.getEndTime());
        Long cid = 1L;
        Long cid1 = 15L;
        if(dto.getTypeLevel() == 2L){
            cid = 2L;
            cid1 = 13L;
        }
        try {
            for(String item: arr){
                TbyAnimalPlantScreenBean vo = new TbyAnimalPlantScreenBean();
                if (sameYear) {
                    vo.setName(Integer.parseInt(ToolsUtil.splitStr(item, '-')[1]) + "月");
                } else {
                    vo.setName(item);
                }
                /*if("0".equals(item.substring(5,6))){
                    vo.setName(item.substring(6,item.length())+"月");
                }else{
                    vo.setName(item.substring(5,item.length())+"月");
                }*/
                DbTableQuery dbTableQuery = db.table("tby_change_trend a")
                        .whereTrue()
                        .andIf(true,"a.species_code = ?", cid)
                        .andIf(true,"a.statistical_time = ?", item)
                        .groupBy("a.statistical_time");//只统计顶级分类以下的
                DbTableQuery dbTableQueryK = db.table("tby_change_trend a")
                        .whereTrue()
                        .andIf(true,"a.species_code = ?", cid1)
                        .andIf(true,"a.statistical_time = ?", item)
                        .groupBy("a.statistical_time");//只统计顶级分类以下的
                List<TbyAnimalPlantScreenBean> listD = dbTableQuery
                        .selectList("sum(a.statistical_num) value, a.statistical_time statistical_time", TbyAnimalPlantScreenBean.class);
                List<TbyAnimalPlantScreenBean> listK = dbTableQueryK
                        .selectList("sum(a.statistical_num) value, a.statistical_time statistical_time", TbyAnimalPlantScreenBean.class);
                if(listD !=null && listD.size()>0){
                    vo.setValue(listD.get(0).getValue());
                }else{
                    vo.setValue(0L);
                }
                if(listK !=null && listK.size()>0){
                    vo.setValue1(listK.get(0).getValue());
                }else{
                    vo.setValue1(0L);
                }
                list.add(vo);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getChangeTrendNew(TbyAnimalPlantScreenQuery dto) throws ParseException {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        String startYear = ToolsUtil.splitStr(dto.getStartTime(), '-')[0];
        String endYear = ToolsUtil.splitStr(dto.getEndTime(), '-')[0];
        // 开始结束时间是同一年的情况下，只显示月份，开始和结束时间不是同一年的情况下，显示yyyy-MM
        boolean sameYear = startYear.equals(endYear);
        ArrayList<String> arr = getMiddleMonthNew(dto.getStartTime(),dto.getEndTime());
        Long cid = 1L;
        Long cid1 = 15L;
        if(dto.getTypeLevel() == 2L){
            cid = 2L;
            cid1 = 13L;
        }
        try {
            for(String item: arr){
                TbyAnimalPlantScreenBean vo = new TbyAnimalPlantScreenBean();

                vo.setName(item);

//                if (sameYear) {
//                    vo.setName(Integer.parseInt(ToolsUtil.splitStr(item, '-')[1]) + "月");
//                } else {
//                    vo.setName(item);
//                }
                /*if("0".equals(item.substring(5,6))){
                    vo.setName(item.substring(6,item.length())+"月");
                }else{
                    vo.setName(item.substring(5,item.length())+"月");
                }*/
                DbTableQuery dbTableQuery = db.table("tby_change_trend a")
                        .whereTrue()
                        .andIf(true,"a.species_code = ?", cid)
                        .andIf(true,"a.statistical_time = ?", item)
                        .groupBy("a.statistical_time");//只统计顶级分类以下的
                DbTableQuery dbTableQueryK = db.table("tby_change_trend a")
                        .whereTrue()
                        .andIf(true,"a.species_code = ?", cid1)
                        .andIf(true,"a.statistical_time = ?", item)
                        .groupBy("a.statistical_time");//只统计顶级分类以下的
                List<TbyAnimalPlantScreenBean> listD = dbTableQuery
                        .selectList("sum(a.statistical_num) value, a.statistical_time statistical_time", TbyAnimalPlantScreenBean.class);
                List<TbyAnimalPlantScreenBean> listK = dbTableQueryK
                        .selectList("sum(a.statistical_num) value, a.statistical_time statistical_time", TbyAnimalPlantScreenBean.class);
                if(listD !=null && listD.size()>0){
                    vo.setValue(listD.get(0).getValue());
                }else{
                    vo.setValue(0L);
                }
                if(listK !=null && listK.size()>0){
                    vo.setValue1(listK.get(0).getValue());
                }else{
                    vo.setValue1(0L);
                }
                list.add(vo);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
        public List<TbyAnimalPlantScreenBean> getfungi(TbyAnimalPlantScreenQuery dto) throws ParseException {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        String startYear = ToolsUtil.splitStr(dto.getStartTime(), '-')[0];
        String endYear = ToolsUtil.splitStr(dto.getEndTime(), '-')[0];
        // 开始结束时间是同一年的情况下，只显示月份，开始和结束时间不是同一年的情况下，显示yyyy-MM
        boolean sameYear = startYear.equals(endYear);
        ArrayList<String> arr = getMiddleMonthNew(dto.getStartTime(),dto.getEndTime());
        Long cid = 13L;
        try {
            for(String item: arr){
                TbyAnimalPlantScreenBean vo = new TbyAnimalPlantScreenBean();
                vo.setName(item);
                DbTableQuery dbTableQuery = db.table("tby_change_trend a")
                        .whereTrue()
                        .andIf(true,"a.species_code = ?", cid)
                        .andIf(true,"a.statistical_time = ?", item)
                        .groupBy("a.statistical_time");//只统计顶级分类以下的
                List<TbyAnimalPlantScreenBean> listD = dbTableQuery
                        .selectList("sum(a.statistical_num) value, a.statistical_time statistical_time", TbyAnimalPlantScreenBean.class);
                if(listD !=null && listD.size()>0){
                    vo.setValue(listD.get(0).getValue());
                }else{
                    vo.setValue(0L);
                }
                list.add(vo);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    public static ArrayList<String> getMiddleMonthNew(String startTime, String endTime) throws ParseException {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(startTime));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(endTime));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.YEAR, 1);
        }
        return result;
    }

    public static ArrayList<String> getMiddleMonth(String startTime, String endTime) throws ParseException {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(startTime));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(endTime));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> getview(Long id) {
        List<TbyAnimalPlantScreenBean> list = new ArrayList<>();
        DbTableQuery dbTableQuery = db.table("tby_education_view v")
                .innerJoin("tby_animal_plant ap").onEq("v.business_id", "ap.id")
                .whereEq("v.category", "WZ")
                .andIf(true,"v.business_id = ?", id);
        try {
            list = dbTableQuery.selectList("v.file_url files, v.thumbnail_url, v.thumbnail_icon", TbyAnimalPlantScreenBean.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public List<TbyAnimalPlantScreenBean> groupByCategory(Long typeLevel) {
        DbTableQuery dbTableQuery = db.table("tby_species_category c")
                .leftJoin("tby_animal_plant a").onEq("a.type_level", "c.id")
                .whereEq("c.parent_id", typeLevel);
        /*if (typeLevel.compareTo(2L) == 0) {
            dbTableQuery.orEq("c.id", 13);
        }*/
        try {
            long total = dbTableQuery.selectCount();
            dbTableQuery.groupBy("c.id, c.category_name")
                    .orderByDesc("num");
            List<TbyAnimalPlantScreenBean> list = dbTableQuery.selectList("c.id, c.category_name as category_name, count(a.id) as num", TbyAnimalPlantScreenBean.class);
            /*if (typeLevel.compareTo(2L) == 0) {
                // 大型菌类因需求不明确，来回改动层级导致只能写死
                List<TbyAnimalPlantScreenBean> resultList = new ArrayList<>();
                for (TbyAnimalPlantScreenBean bean : list) {
                    if (bean.getId().compareTo(17L) != 0) {
                        bean.setTotal(total);
                        BigDecimal percent = BigDecimal.valueOf(bean.getNum()).divide(BigDecimal.valueOf(total),4,ROUND_HALF_UP);
                        bean.setPercent(percent.multiply(new BigDecimal("100")));
                        resultList.add(bean);
                    }
                }
                return resultList;
            }*/
            list.forEach(item -> {
                item.setTotal(total);
                BigDecimal percent = BigDecimal.valueOf(item.getNum()).divide(BigDecimal.valueOf(total),4,ROUND_HALF_UP);
                item.setPercent(percent.multiply(new BigDecimal("100")));
            });
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<SpeciesLegendBean> getLegendByParentId(Long speciesParentId) {
        List<SpeciesLegendBean> dataList = new ArrayList<>();
        if (speciesParentId == null) {
            return dataList;
        }
        try {
            DbTableQuery dbTableQuery = db.table("tby_animal_plant a").innerJoin("tby_species_category c")
                    .onEq("a.type_level", "c.id").whereEq("c.parent_id", speciesParentId).andEq("a.legend", 1);
            List<TbyAnimalPlant> dbList = dbTableQuery.selectList("a.id, a.ch_name, a.files, a.thumbnail, a.thumbnail_icon, a.latitude_longitude", TbyAnimalPlant.class);
            if (dbList != null) {
                for (TbyAnimalPlant tbyAnimalPlant : dbList) {
                    dataList.add(new SpeciesLegendBean(tbyAnimalPlant));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dataList;
    }

    @Override
    public Long searchTotalCountByCherish(Integer val, Long topId) {
        DbTableQuery dbTableQuery = db.table("tby_animal_plant a")
                .innerJoin("tby_species_category c").onEq("a.type_level", "c.id")
                .whereTrue()
                .andIf(true,"(c.id = ?", topId).or("c.parent_id = ?)", topId)
                .andEq("a.is_cherish", val);
        try {
            return dbTableQuery.selectCount();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0L;
    }
}
